//
//  OAuthViewController.swift
//  MySinaWeibo
//
//  Created by apple on 15/11/4.
//  Copyright © 2015年 baidu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    
//    MARK: - 搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
/// 关闭界面
    func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
 
//        加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthUrl()))
    }

// MARK: - UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
//        print("开始")
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
//        print("结束")
        SVProgressHUD.dismiss()
    }
    
    /**
    1. 如果请求的URL包含回调地址，需要判断参数，否则继续加载
    2. 如果请求参数中，包含code,可以从请求的url中获得请求码
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
//        判断是否包含回调地址
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUri) {
            
            return true
        }
        print("判断参数")
        print(request.URL?.query)
        if let query = request.URL?.query where query.hasPrefix("code=") {
            
            print("获取授权码")
//            从query中截取授权码
//            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            let code = (query as NSString).substringFromIndex(5)
            print(code)
            loadAccessToken(code)
            
        } else{
        
            close()
        }
        
//        print(request)
        return false
    }
    
    private func loadAccessToken(code: String) {
    
//        NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
//            if error != nil || result == nil {
//                
//                SVProgressHUD.showInfoWithStatus("您的网络不给力")
//                
////                延时一段时间再关闭
//                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
//                dispatch_after(when, dispatch_get_main_queue()) {
//                    self.close()
//                }
//               
//                return
//            }
//        
////            字典转模型
//            let account = UserAccount(dict: result!)
//            account.saveAccount()
////            用户登录后，加载当前用户的个人信息
//            NetWorkTools.sharedTools.loadUserInfo(account.uid!, finished: { (result, error) -> () in
//                print(result)
//            })
//            print(account)
//            print(result)
//            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
//                if error != nil {
//                    SVProgressHUD.showInfoWithStatus("您的网络不给力")
//                    
//                    //                延时一段时间再关闭
//                    let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
//                    dispatch_after(when, dispatch_get_main_queue()) {
//                        self.close()
//                    }
//
//                    return
//                }
//                print("OK")
//            })
//        }
        
        
        NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                
                self.netError()
                return
            }
            
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    
                    self.netError()
                    return
                }
                
//                发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(LNRootViewControllerSwitchNotification, object: false)
                
//                关闭控制器,Modal出来的控制器，一定注意需要dismiss!
                self.close()
            })
        }
        
        

    }
    deinit {
        
        print("88")
    }


/// 网络出错处理
    private func netError() {
        
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        //                延时一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            self.close()
    }

}

}


























